package com.example.singletask.util

import io.reactivex.Observable
import io.reactivex.android.schedulers.AndroidSchedulers
import io.reactivex.disposables.Disposable
import io.reactivex.schedulers.Schedulers
import java.util.concurrent.TimeUnit

/**
 * 定时器任务
 * @param initialDelay  启动延时，单位：毫秒
 * @param interval      周期，单位：毫秒
 * @param action        定时器执行内容（次数:Long，当前时间戳:Long）
 *
 */
open class TimerTask(val initialDelay: Long = 10,
                     val interval: Long = 1000,
                     var action: (timer: TimerTask, tick: Tick) -> Unit) {

    private var disposable: Disposable? = null
    private var mainThread: Boolean = true
    private var running: Boolean = false
    private var startTime: Long = 0L
    private var tick: Tick = Tick()

    val isRunning: Boolean
        get() = disposable!= null &&
                !disposable!!.isDisposed &&
                running

    /**
     * 设定在子线程上运行
     */
    fun runOnThread(): TimerTask {
        mainThread = false
        return this
    }

    fun start(): TimerTask {
        stop()

        startTime = System.currentTimeMillis()
        running = true

        val scheduler = if(mainThread) AndroidSchedulers.mainThread() else Schedulers.newThread()
        disposable = Observable
            .interval(initialDelay,interval,TimeUnit.MILLISECONDS,scheduler)
            .subscribe{time ->
                tick.startTime = startTime
                tick.currentTime = System.currentTimeMillis()
                tick.counter = time + 1

                action.invoke(this,tick)
            }
        return this
    }

    fun stop(){
        running = false
        disposable?.dispose()
    }

    class Tick {
        var startTime = 0L
        var currentTime = 0L
        var counter = 0L
        override fun toString(): String {
            return "startTime=$startTime, currentTime=$currentTime, counter=$counter"
        }

    }
}